const Service = require('egg').Service;

class NewsService extends Service {
  async list(page = 1) {
    
    // read config
    const { serverUrl, pageSize } = this.config.news;

    // this.ctx.log('service/news.js list() 执行了 this.config.news', this.config.news);
    console.log('service/news.js list() 执行了 this.config.news', this.config.news);

    // use build-in http client to GET hacker-news api
    // const { data: idList } = await this.ctx.curl(`${serverUrl}/news`, {
    const ret = await this.ctx.curl(`${serverUrl}/news`, {
      // method: 'post',// 默认是 get，所以 data 里面的字段都在 this.ctx.query 里面
      // （当然由于每个key对应一个值，所以 this.ctx.queries 值一致），此时 this.ctx.query.body 是没有东西的。
      // 而当改为 post 后，框架提示缺少 csrf token；
      data: {
        orderBy: '"$key"',
        startAt: `"${pageSize * (page - 1)}"`,
        endAt: `"${pageSize * page - 1}"`,
      },
      dataType: 'json',
    });
    // this.ctx.log('service/news.js list() 执行了 ret', ret);
    console.log('service/news.js list() 执行了 ret', ret);
    /*
    {
        "data": [{
            "id": 1,
            "title": "news1"
        },
        {
            "id": 2,
            "title": "news2"
        },
        {
            "id": 3,
            "title": "news3"
        }],

        "status": 200,
        "headers": {
            "set-cookie": ["csrfToken=d_birLP5C66I26-autkxXqHJ; path=/"],
            "content-type": "application/json; charset=utf-8",
            "x-frame-options": "SAMEORIGIN",
            "x-xss-protection": "1; mode=block",
            "x-content-type-options": "nosniff",
            "x-download-options": "noopen",
            "x-readtime": "3",
            "keep-alive": "timeout=5",
            "content-length": "85",
            "date": "Fri, 30 Nov 2018 03:13:11 GMT",
            "connection": "keep-alive"
        },
        "res": {
            "status": 200,
            "statusCode": 200,
            "headers": {
                "set-cookie": ["csrfToken=d_birLP5C66I26-autkxXqHJ; path=/"],
                "content-type": "application/json; charset=utf-8",
                "x-frame-options": "SAMEORIGIN",
                "x-xss-protection": "1; mode=block",
                "x-content-type-options": "nosniff",
                "x-download-options": "noopen",
                "x-readtime": "3",
                "keep-alive": "timeout=5",
                "content-length": "85",
                "date": "Fri, 30 Nov 2018 03:13:11 GMT",
                "connection": "keep-alive"
            },
            "size": 85,
            "aborted": false,
            "rt": 21,
            "keepAliveSocket": false,
            "data": {
                "data": [{
                    "id": 1,
                    "title": "news1"
                },
                {
                    "id": 2,
                    "title": "news2"
                },
                {
                    "id": 3,
                    "title": "news3"
                }]
            },
            "requestUrls": ["http://127.0.0.1:7001/news"],
            "timing": null,
            "remoteAddress": "127.0.0.1",
            "remotePort": 7001,
            "socketHandledRequests": 1,
            "socketHandledResponses": 1
        }
    }
     *--/
    
    let { data: idList } = ret;
    // this.ctx.log('service/news.js list() 执行了 { data: idList }', { data: idList });
    console.log('service/news.js list() 执行了 { data: idList }', { data: idList });

    return idList;
    
   
   // 当在 app.js 中执行
   // const ctx = app.createAnonymousContext();
   // let res2 = await ctx.service.news.list(1);
   // 时，下面是可以的；但上面的有问题，项目启动失败，具体原因不明--我估计是因为项目还未成功启动，所以不能通过控制器来访自身的东西；

   // return [{id:1,title:'title1'}, {id:2,title:'title2'}];
  }

  async list2(page = 1) {
    // read config
    const { serverUrl, pageSize } = this.config.news;

    // use build-in http client to GET hacker-news api
    const ret = await this.ctx.curl(`${serverUrl}/public/topstories.json`, {
      data: {
        orderBy: '"$key"',
        startAt: `"${pageSize * (page - 1)}"`,
        endAt: `"${pageSize * page - 1}"`,
      },
      dataType: 'json',
    });
    this.ctx.log('service/news.js list2() 执行了 ret', ret);

    let { data: idList } = ret;
    this.ctx.log('service/news.js list2() 执行了 { data: idList }', { data: idList });
    
    // parallel GET detail
    const newsList = await Promise.all(
      Object.keys(idList).map(key => {
        // this.ctx.log('service/news.js list2() 执行了 key', key);// 0,1,2;
        const url = `${serverUrl}/public/item/${idList[key].id}.json`;
        return this.ctx.curl(url, { dataType: 'json' });
      })
    );
    this.ctx.log('service/news.js list2() 执行了 newsList', newsList);
    /*
    [{
        "data": {
            "id": 1,
            "title": "topstories.json news1",
            "content": "topstories.json news1  topstories.json news1  topstories.json news1"
        },
        "status": 200,
        "headers": {
            "accept-ranges": "bytes",
            "last-modified": "Fri, 30 Nov 2018 03:45:10 GMT",
            "etag": "\"TCmRGg3HtIO8K5b+4e/frg==\"",
            "content-type": "application/json; charset=utf-8",
            "content-length": "137",
            "cache-control": "public, max-age=0",
            "content-md5": "TCmRGg3HtIO8K5b+4e/frg==",
            "x-readtime": "2",
            "keep-alive": "timeout=5",
            "date": "Fri, 30 Nov 2018 03:46:17 GMT",
            "connection": "keep-alive"
        },
        "res": {
            "status": 200,
            "statusCode": 200,
            "headers": {
                "accept-ranges": "bytes",
                "last-modified": "Fri, 30 Nov 2018 03:45:10 GMT",
                "etag": "\"TCmRGg3HtIO8K5b+4e/frg==\"",
                "content-type": "application/json; charset=utf-8",
                "content-length": "137",
                "cache-control": "public, max-age=0",
                "content-md5": "TCmRGg3HtIO8K5b+4e/frg==",
                "x-readtime": "2",
                "keep-alive": "timeout=5",
                "date": "Fri, 30 Nov 2018 03:46:17 GMT",
                "connection": "keep-alive"
            },
            "size": 137,
            "aborted": false,
            "rt": 11,
            "keepAliveSocket": true,
            "data": {
                "id": 1,
                "title": "topstories.json news1",
                "content": "topstories.json news1  topstories.json news1  topstories.json news1"
            },
            "requestUrls": ["http://127.0.0.1:7001/public/item/1.json"],
            "timing": null,
            "remoteAddress": "127.0.0.1",
            "remotePort": 7001,
            "socketHandledRequests": 3,
            "socketHandledResponses": 3
        }
    },
    {
        "data": {
            "id": 2,
            "title": "topstories.json news2",
            "content": "topstories.json news2  topstories.json news2  topstories.json news2"
        },
        "status": 200,
        "headers": {
            "accept-ranges": "bytes",
            "last-modified": "Fri, 30 Nov 2018 03:45:54 GMT",
            "etag": "\"zn7gEx+etIcdDtmlbOqNSw==\"",
            "content-type": "application/json; charset=utf-8",
            "content-length": "137",
            "cache-control": "public, max-age=0",
            "content-md5": "zn7gEx+etIcdDtmlbOqNSw==",
            "x-readtime": "1",
            "keep-alive": "timeout=5",
            "date": "Fri, 30 Nov 2018 03:46:17 GMT",
            "connection": "keep-alive"
        },
        "res": {
            "status": 200,
            "statusCode": 200,
            "headers": {
                "accept-ranges": "bytes",
                "last-modified": "Fri, 30 Nov 2018 03:45:54 GMT",
                "etag": "\"zn7gEx+etIcdDtmlbOqNSw==\"",
                "content-type": "application/json; charset=utf-8",
                "content-length": "137",
                "cache-control": "public, max-age=0",
                "content-md5": "zn7gEx+etIcdDtmlbOqNSw==",
                "x-readtime": "1",
                "keep-alive": "timeout=5",
                "date": "Fri, 30 Nov 2018 03:46:17 GMT",
                "connection": "keep-alive"
            },
            "size": 137,
            "aborted": false,
            "rt": 16,
            "keepAliveSocket": false,
            "data": {
                "id": 2,
                "title": "topstories.json news2",
                "content": "topstories.json news2  topstories.json news2  topstories.json news2"
            },
            "requestUrls": ["http://127.0.0.1:7001/public/item/2.json"],
            "timing": null,
            "remoteAddress": "127.0.0.1",
            "remotePort": 7001,
            "socketHandledRequests": 1,
            "socketHandledResponses": 1
        }
    },
    {
        "data": {
            "id": 3,
            "title": "topstories.json news3",
            "content": "topstories.json news3  topstories.json news3  topstories.json news3"
        },
        "status": 200,
        "headers": {
            "accept-ranges": "bytes",
            "last-modified": "Fri, 30 Nov 2018 03:45:43 GMT",
            "etag": "\"tZ4dYRsOgxP1WFCP68TuPg==\"",
            "content-type": "application/json; charset=utf-8",
            "content-length": "137",
            "cache-control": "public, max-age=0",
            "content-md5": "tZ4dYRsOgxP1WFCP68TuPg==",
            "x-readtime": "1",
            "keep-alive": "timeout=5",
            "date": "Fri, 30 Nov 2018 03:46:17 GMT",
            "connection": "keep-alive"
        },
        "res": {
            "status": 200,
            "statusCode": 200,
            "headers": {
                "accept-ranges": "bytes",
                "last-modified": "Fri, 30 Nov 2018 03:45:43 GMT",
                "etag": "\"tZ4dYRsOgxP1WFCP68TuPg==\"",
                "content-type": "application/json; charset=utf-8",
                "content-length": "137",
                "cache-control": "public, max-age=0",
                "content-md5": "tZ4dYRsOgxP1WFCP68TuPg==",
                "x-readtime": "1",
                "keep-alive": "timeout=5",
                "date": "Fri, 30 Nov 2018 03:46:17 GMT",
                "connection": "keep-alive"
            },
            "size": 137,
            "aborted": false,
            "rt": 18,
            "keepAliveSocket": false,
            "data": {
                "id": 3,
                "title": "topstories.json news3",
                "content": "topstories.json news3  topstories.json news3  topstories.json news3"
            },
            "requestUrls": ["http://127.0.0.1:7001/public/item/3.json"],
            "timing": null,
            "remoteAddress": "127.0.0.1",
            "remotePort": 7001,
            "socketHandledRequests": 1,
            "socketHandledResponses": 1
        }
    }]
     */
    let ret2 = newsList.map(res => res.data);
    this.ctx.log('service/news.js list2() 执行了 ret2', ret2);
    /*
    [ { id: 1,
      title: 'topstories.json news1',
      content: 'topstories.json news1  topstories.json news1  topstories.json news1' },
    { id: 2,
      title: 'topstories.json news2',
      content: 'topstories.json news2  topstories.json news2  topstories.json news2' },
    { id: 3,
      title: 'topstories.json news3',
      content: 'topstories.json news3  topstories.json news3  topstories.json news3' } ]

     */
    
    // return idList;
    return ret2;
  }
}

module.exports = NewsService;